<?php
namespace App\Controller;

use Cake\Network\Exception\NotFoundException;
use Cake\ORM\TableRegistry;
use Cake\I18n\Time;

class AccountsController extends AppController{
    function index(){
        $this->getAccountByProject();
        $this->getRoleToDropdownList();
    }
    function checkAccountInfo($username, $password){
        $conditions = ['username' => $username, 'password' => md5($password), 'is_delete <>' => '1'];
        $result = $this->Accounts->find()->where($conditions)->first();
        return $result;
    }
    function login(){
        $this->layout = FALSE;
        if (isset($_COOKIE['TMS'])) {
            $username = $_COOKIE['TMS']['username'];
            // Select the username from the cookie
            $password = $_COOKIE['TMS']['password'];
            // Select the password from the cookie
            $result = $this->checkAccountInfo($username, $password);
            if (empty($result)) {
                $this->redirect('/Accounts/login');
            } else {
                $this->setAccountInfo($result);
                $this->set('role', $result['role_id']);
                $this->redirect('/Pages');
            }
        } else {
            $data = $this->request->data();
            if (!empty($data)) {
                $username = $data['username'];
                $password = $data['password'];
                if (isset($_POST['remember']))
                    $check = $_POST['remember'];
                else
                    $check = false;
                $time = time();
                $result = $this->checkAccountInfo($username, $password);
                if (empty($result)) {
                    $this->set('error_message', 'Invalid username or password.');
                } else {
                    $this->setAccountInfo($result);
                    $this->set('role', $result['role_id']);
                    if ($check) {
                        setcookie('TMS[username]', $username, $time + 3600);
                        setcookie('TMS[password]', $password, $time + 3600);
                    }
                    $this->redirect('/Pages');
                }
            }
        }
    }
    function logout(){
        if (isset($_COOKIE['TMS'])) {
            $time = time();
            setcookie("TMS[username]", '', $time - 3600);
            setcookie("TMS[password]", '', $time - 3600);
        }
        $this->setAccountInfo(null);
        $this->redirect('/Accounts/login');
    }
    function deActiveAccount($account_id){
        $accounts = TableRegistry::get('Accounts');
        $account = $accounts->find('all')->where(['id' => $account_id])->first();
        $account->is_delete = 1;
        $account->updated_date = date('y/m/d H:i:s');
        $account->id = $account_id;
        $accounts->save($account);
        $account = $this->Accounts->findById($account_id);
        $this->set('account', $account);
        $this->render('account_button');
    }
    function activeAccount($account_id){

        $accounts = TableRegistry::get('Accounts');
        $account = $accounts->find('all')->where(['id' => $account_id])->first();
        $account->is_delete = 0;
        $account->updated_date = date('y/m/d H:i:s');
        $account->id = $account_id;
        $accounts->save($account);

        $account = $this->Accounts->findById($account_id);
        $this->set('account', $account);
        $this->render('account_button');
    }
    function addNewAccount(){
        $this->getRoleToDropdownList();
        $this->getTeamToDropdownList();
        if ($this->request->data()) {
            $password = 'demo';
            $data = $this->request->data();
            $accounts = TableRegistry::get('Accounts');
            $entity = $accounts->newEntity($data, ['fieldList'=>['password'=>md5($password),
                                                                    'created_date'=> date('y/m/d H:i:s'),
                                                                    ]]);
            if ($_FILES)
                if ($_FILES['image']['name']) {
                    $path = $_FILES['image']['name'];
                    $ext = pathinfo($path, PATHINFO_EXTENSION);
                    $sFileName = $this->generateRandomString() . '.' . $ext;
                    $file_uri = '/upload/image/' . $sFileName;
                    $data['Account']['image'] = $file_uri;
                    move_uploaded_file($_FILES['image']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/app/webroot' . $file_uri);
                }
            }
            $this->Account->save($data);
            if (isset($data['Account']['id'])) {
                $acc = $this->getAccountInfo();
                if ($acc['Account']['id'] == $data['Account']['id']) {
                    $acc = $this->Account->find('first', array('conditions' => array('Account.id' => $acc['Account']['id'])));
                    $this->setAccountInfo($acc);
                }
            }
            $this->redirect('/Accounts');
    }
    function editAccount($account_id = null){
        if (empty($account_id)) {
            throw new NotFoundException;
        }
        $account = $this->Accounts->get($account_id);
        // Save logic goes here
        $this->set('account', $account);
    }

    function getAccountByProject(){
        $acc = $this->getAccountInfo();
        $account_id = $acc['id'];
        $team_id = $acc['team_id'];
        $role_id = $acc['role_id'];
        if ($role_id == ROLE_ADMIN) {
            $account = $this->Accounts->find('all', array('order' => array('Account.created_date' => 'desc'), 'conditions' => array('Account.role_id <>' => ROLE_ADMIN)));
        } elseif ($role_id == ROLE_PROJECT_MANAGER) {
            $account = $this->Accounts->find('all', array('order' => array('Account.created_date' => 'desc'), 'conditions' => array('Account.role_id <>' => ROLE_ADMIN, 'Account.role_id >=' => ROLE_PROJECT_MANAGER, 'Account.id <>' => $account_id, 'Account.team_id' => $team_id)));
        } else { // leader
            $account = $this->Accounts->find()
                ->where(['Accounts.role_id <>' => ROLE_ADMIN,'Accounts.role_id >=' => ROLE_LEADER,'Accounts.id <>'=>$account_id, 'Accounts.team_id' => $team_id])
                ->order(['Accounts.created_date' => 'DESC'])
                ->all();
        }
        $this->set('account', $account);
    }
    function getRoleToDropdownList(){
        $this->loadModel('Roles');
        $acc = $this->getAccountInfo();
        $role_id = $acc['role_id'];
        $role_list = $this->Roles->find('list', ['idField'=>'id', 'valueField'=>'name'])
            ->where(['id >=' => $role_id, 'id >' => ROLE_ADMIN])->toArray();
        $this->set('role_list', $role_list);
    }
    function getTeamToDropdownList(){
        $acc = $this->getAccountInfo();
        $team_id = $acc['team_id'];
        $role_id = $acc['role_id'];
        if ($role_id == ROLE_ADMIN) {
            $team = $this->Teams->find('list', array('fields' => array('name')));
        } elseif ($role_id == ROLE_PROJECT_MANAGER) {
            //TODO
        } else {
            $team = $this->Teams->find('list', array('fields' => array('name'), 'conditions' => array('id' => $team_id)));
        }
        $team = array_unique($team);
        $this->set('team', $team);
    }
}

?>